/*
 * 10.4.cpp 1661_poj
 *
 *  Created on: 2012-5-24
 *      Author: ncrd
 */


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>

using namespace std;

#define N 1001
#define INFINITE 1000000

struct PLATFORM {
	int left, right, height;
};

PLATFORM platform[N];
int minLeft[N], minRight[N];
int num, maxSpeed;;

int compare(const void * a, const void *b) {
	return ((PLATFORM *)b)->height - ((PLATFORM *)a)->height;
}

int minTime(int i, bool isLeft) {
	int x;
	if (isLeft) x=platform[i].left;
	else x=platform[i].right;
	int j;
	for (j=i+1; j<=num; j++) {
		if (x >= platform[j].left && x <= platform[j].right)
			break;
	}
	if (j>num) {
		if (platform[i].height > maxSpeed) {
			return INFINITE;
		} else {
			return platform[i].height;
		}
	} else {
		if (platform[i].height - platform[j].height > maxSpeed)
			return INFINITE;
	}
	int nLeftTime = platform[i].height - platform[j].height + x - platform[j].left;
	int nRightTime = platform[i].height - platform[j].height + platform[j].right - x;
	if (minLeft[i] == -1)
		minLeft[i] = minTime(j, true);
	if (minRight[i] == -1)
		minRight[i] = minTime(j, false);
	nLeftTime += minLeft[i];
	nRightTime += minRight[i];
	return min(nLeftTime, nRightTime);
}

int main (void) {
	int n;
	scanf("%d", &n);
	while (n--) {
		scanf("%d%d%d%d", &num, &platform[0].left, &platform[0].height, &maxSpeed);
		platform[0].right = platform[0].left;
		memset(minLeft, -1, sizeof(minLeft));
		memset(minRight, -1, sizeof(minRight));
		for (int i=1; i<=num; i++) {
			scanf("%d %d %d", &platform[i].left, &platform[i].right, &platform[i].height);
		}
		qsort(platform, num+1, sizeof(PLATFORM), compare);
		printf("%d\n", minTime(0, true));
	}
	return 0;
}
